"""
定时任务调度器管理API
提供启动、停止、查看、手动触发定时任务的接口
"""

from flask import Blueprint, request, jsonify
from app.services.scheduler_service import get_scheduler, start_scheduler, stop_scheduler
from app.utils.logger import FlinkLogger, log_business_logic

# 延迟初始化logger，避免应用上下文问题
logger = None

def get_logger():
    global logger
    if logger is None:
        logger = FlinkLogger.get_logger(__name__)
    return logger

scheduler_bp = Blueprint('scheduler', __name__, url_prefix='/api/scheduler')


@scheduler_bp.route('/status', methods=['GET'])
@log_business_logic("获取调度器状态")
def get_scheduler_status():
    """获取调度器和任务状态"""
    try:
        scheduler = get_scheduler()
        status = scheduler.get_job_status()
        return jsonify({
            'success': True,
            'data': status
        })
    except Exception as e:
        get_logger().error(f"❌ 获取调度器状态失败: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/start', methods=['POST'])
@log_business_logic("启动调度器")
def start_scheduler_api():
    """启动调度器"""
    try:
        scheduler = start_scheduler()
        return jsonify({
            'success': True,
            'message': '调度器启动成功',
            'data': scheduler.get_job_status()
        })
    except Exception as e:
        get_logger().error(f"❌ 启动调度器失败: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/stop', methods=['POST'])
@log_business_logic("停止调度器")
def stop_scheduler_api():
    """停止调度器"""
    try:
        stop_scheduler()
        return jsonify({
            'success': True,
            'message': '调度器已停止'
        })
    except Exception as e:
        get_logger().error(f"❌ 停止调度器失败: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/jobs/<job_id>/enable', methods=['POST'])
@log_business_logic("启用定时任务")
def enable_job_api(job_id: str):
    """启用指定任务"""
    try:
        scheduler = get_scheduler()
        success = scheduler.enable_job(job_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': f'任务 {job_id} 已启用'
            })
        else:
            return jsonify({
                'success': False,
                'error': f'任务 {job_id} 不存在'
            }), 404
            
    except Exception as e:
        get_logger().error(f"❌ 启用任务失败 {job_id}: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/jobs/<job_id>/disable', methods=['POST'])
@log_business_logic("禁用定时任务")
def disable_job_api(job_id: str):
    """禁用指定任务"""
    try:
        scheduler = get_scheduler()
        success = scheduler.disable_job(job_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': f'任务 {job_id} 已禁用'
            })
        else:
            return jsonify({
                'success': False,
                'error': f'任务 {job_id} 不存在'
            }), 404
            
    except Exception as e:
        get_logger().error(f"❌ 禁用任务失败 {job_id}: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/jobs/<job_id>/trigger', methods=['POST'])
@log_business_logic("手动触发定时任务")
def trigger_job_api(job_id: str):
    """手动触发指定任务"""
    try:
        scheduler = get_scheduler()
        success = scheduler.trigger_job_now(job_id)
        
        if success:
            return jsonify({
                'success': True,
                'message': f'任务 {job_id} 已手动触发'
            })
        else:
            return jsonify({
                'success': False,
                'error': f'任务 {job_id} 不存在或调度器未运行'
            }), 404
            
    except Exception as e:
        get_logger().error(f"❌ 手动触发任务失败 {job_id}: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/jobs', methods=['GET'])
@log_business_logic("获取任务配置列表")
def get_job_configs():
    """获取所有任务配置"""
    try:
        scheduler = get_scheduler()
        configs = scheduler._job_configs
        
        # 转换为前端友好的格式
        job_list = []
        for job_id, config in configs.items():
            job_info = {
                'id': job_id,
                'name': config['name'],
                'description': config.get('description', ''),
                'method': config['method'],
                'database': config.get('database', ''),
                'enabled': config.get('enabled', False),
                'trigger_type': config['trigger'],
                'trigger_config': {}
            }
            
            # 添加触发器配置
            if config['trigger'] == 'cron':
                job_info['trigger_config'] = {
                    'hour': config.get('hour'),
                    'minute': config.get('minute', 0),
                    'second': config.get('second', 0)
                }
            elif config['trigger'] == 'interval':
                job_info['trigger_config'] = {
                    'hours': config.get('hours', 0),
                    'minutes': config.get('minutes', 0),
                    'seconds': config.get('seconds', 0)
                }
            
            job_list.append(job_info)
        
        return jsonify({
            'success': True,
            'data': {
                'jobs': job_list,
                'total': len(job_list)
            }
        })
        
    except Exception as e:
        get_logger().error(f"❌ 获取任务配置失败: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@scheduler_bp.route('/history', methods=['GET'])
@log_business_logic("获取任务执行历史")
def get_job_history():
    """获取任务执行历史"""
    try:
        from app.utils.mysql_db import get_db_cursor
        
        # 获取查询参数
        job_id = request.args.get('job_id')
        limit = request.args.get('limit', 50, type=int)
        offset = request.args.get('offset', 0, type=int)
        
        with get_db_cursor() as cursor:
            # 构建查询条件
            where_clause = ""
            params = []
            
            if job_id:
                where_clause = "WHERE job_id = %s"
                params.append(job_id)
            
            # 查询总数
            cursor.execute(f"SELECT COUNT(*) as total FROM scheduled_job_history {where_clause}", params)
            total = cursor.fetchone()['total']
            
            # 查询历史记录
            cursor.execute(f"""
                SELECT job_id, success, processed_tables, success_tables, failed_tables,
                       elapsed_seconds, error_message, executed_at
                FROM scheduled_job_history 
                {where_clause}
                ORDER BY executed_at DESC
                LIMIT %s OFFSET %s
            """, params + [limit, offset])
            
            history = cursor.fetchall()
            
            return jsonify({
                'success': True,
                'data': {
                    'history': history,
                    'total': total,
                    'limit': limit,
                    'offset': offset
                }
            })
            
    except Exception as e:
        get_logger().error(f"❌ 获取任务历史失败: {e}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
